/**
 * 现场调查管理服务层
 */

// 模拟调查报告数据
const mockInvestigationReports = [
  {
    id: 'INV-2025-1101',
    title: '新冠肺炎聚集性疫情现场调查报告',
    caseInfo: '病例编号: CASE-2025-0156',
    investigator: '流调专员 韩梅',
    investigateTime: '2025-11-05 10:30',
    location: '江北区某商务楼宇',
    status: '已完成',
    priority: '高',
    contactCount: 45,
    closeContactCount: 12,
    summary: '经调查，该商务楼宇7楼某公司出现3例新冠肺炎确诊病例，发病前14天内曾参加同一会议。现场调查显示，会议室通风不良，参会人员未佩戴口罩。已追踪密切接触者12人，次密接触者33人，均已落实隔离医学观察措施。',
    measures: [
      '对确诊病例活动轨迹进行详细追溯',
      '排查密切接触者和次密接触者',
      '对涉及场所进行终末消毒',
      '要求相关人员落实健康监测',
      '强化楼宇疫情防控措施'
    ],
    riskLevel: '中风险',
    createTime: '2025-11-05 10:30',
    updateTime: '2025-11-05 16:20',
    shareCount: 5,
    exportCount: 2
  },
  {
    id: 'INV-2025-1098',
    title: '诺如病毒感染聚集性疫情调查',
    caseInfo: '病例编号: CASE-2025-0142',
    investigator: '流调组长 钱峰',
    investigateTime: '2025-11-04 09:15',
    location: '南山区某小学',
    status: '已完成',
    priority: '中',
    contactCount: 28,
    closeContactCount: 8,
    summary: '某小学三年级2班出现多名学生呕吐、腹泻症状。经流行病学调查和实验室检测，确诊为诺如病毒感染。调查显示，该班级近期举办班级聚餐，部分学生食用了未彻底加热的海鲜食品。已对患病学生进行隔离治疗，对教室和公共区域进行消毒处理。',
    measures: [
      '隔离治疗患病学生',
      '对教室进行全面消毒',
      '加强晨午检和因病缺勤登记',
      '开展健康教育和卫生指导',
      '暂停班级集体活动'
    ],
    riskLevel: '低风险',
    createTime: '2025-11-04 09:15',
    updateTime: '2025-11-04 18:45',
    shareCount: 3,
    exportCount: 1
  },
  {
    id: 'INV-2025-1095',
    title: '手足口病疫情现场调查报告',
    caseInfo: '病例编号: CASE-2025-0138',
    investigator: '流调专员 周洁',
    investigateTime: '2025-11-03 14:00',
    location: '东区某幼儿园',
    status: '进行中',
    priority: '高',
    contactCount: 52,
    closeContactCount: 15,
    summary: '东区某幼儿园中班出现多例手足口病病例。经调查，该班级共有幼儿28人，已发病5人。所有患儿均出现发热、口腔疱疹和手足皮疹等典型症状。调查发现，该班级玩具消毒不及时，部分幼儿有吮吸手指习惯。已启动应急响应，加强环境消毒和健康监测。',
    measures: [
      '患病幼儿居家隔离治疗',
      '加强晨检和全日健康观察',
      '每日对玩具和环境消毒',
      '开展家长健康教育',
      '监测疫情发展态势'
    ],
    riskLevel: '中风险',
    createTime: '2025-11-03 14:00',
    updateTime: '2025-11-05 11:30',
    shareCount: 4,
    exportCount: 1
  },
  {
    id: 'INV-2025-1089',
    title: '流感样病例聚集性疫情调查',
    caseInfo: '病例编号: CASE-2025-0125',
    investigator: '流调副组长 吴雪',
    investigateTime: '2025-11-02 16:30',
    location: '西湖区某养老院',
    status: '已完成',
    priority: '高',
    contactCount: 35,
    closeContactCount: 10,
    summary: '西湖区某养老院出现流感样病例聚集性疫情，10名老年人出现发热、咳嗽等症状。经实验室检测确诊为甲型H3N2流感病毒感染。调查发现该养老院未按要求开展流感疫苗接种，室内通风不良。已对患者实施隔离治疗，对密切接触者进行医学观察，并安排应急接种。',
    measures: [
      '隔离治疗确诊患者',
      '密切接触者医学观察',
      '开展应急流感疫苗接种',
      '加强室内通风和消毒',
      '每日健康监测和报告'
    ],
    riskLevel: '中风险',
    createTime: '2025-11-02 16:30',
    updateTime: '2025-11-03 20:15',
    shareCount: 6,
    exportCount: 3
  },
  {
    id: 'INV-2025-1082',
    title: '水痘疫情现场流行病学调查',
    caseInfo: '病例编号: CASE-2025-0115',
    investigator: '流调专员 郑云',
    investigateTime: '2025-11-01 10:00',
    location: '北区某中学',
    status: '已完成',
    priority: '中',
    contactCount: 40,
    closeContactCount: 12,
    summary: '北区某中学初二年级出现水痘病例聚集。经调查，该年级4个班级共发现8例水痘病例，均未接种水痘疫苗。病例之间存在明确的流行病学关联，发病间隔符合水痘传播特征。已要求患者居家隔离至结痂脱落，对易感接触者开展应急接种。',
    measures: [
      '患者居家隔离至痊愈',
      '开展水痘疫苗应急接种',
      '加强教室通风和消毒',
      '每日晨检和症状监测',
      '健康教育和防控指导'
    ],
    riskLevel: '低风险',
    createTime: '2025-11-01 10:00',
    updateTime: '2025-11-02 15:00',
    shareCount: 2,
    exportCount: 1
  },
  {
    id: 'INV-2025-1075',
    title: '食源性疾病暴发调查报告',
    caseInfo: '病例编号: CASE-2025-0098',
    investigator: '流调组长 冯涛',
    investigateTime: '2025-10-31 20:00',
    location: '江南区某餐厅',
    status: '已完成',
    priority: '高',
    contactCount: 65,
    closeContactCount: 22,
    summary: '某餐厅发生食源性疾病暴发事件，22名就餐者出现腹痛、腹泻、呕吐等症状。经调查，所有患者均在该餐厅用餐，共同暴露史为食用海鲜拼盘。实验室检测显示为副溶血性弧菌感染。现场检查发现该餐厅存在生熟不分、交叉污染等食品安全隐患。',
    measures: [
      '对患者进行医疗救治',
      '封存可疑食品送检',
      '暂停餐厅营业整改',
      '开展食品安全专项检查',
      '追溯食材来源和供应链'
    ],
    riskLevel: '中风险',
    createTime: '2025-10-31 20:00',
    updateTime: '2025-11-01 22:30',
    shareCount: 8,
    exportCount: 4
  },
  {
    id: 'INV-2025-1068',
    title: '麻疹病例接触者追踪调查',
    caseInfo: '病例编号: CASE-2025-0089',
    investigator: '流调专员 叶明',
    investigateTime: '2025-10-30 15:30',
    location: '市中心医院门诊',
    status: '已完成',
    priority: '高',
    contactCount: 38,
    closeContactCount: 9,
    summary: '一例外地输入麻疹病例在我市某医院门诊就诊期间，可能造成多人暴露。经流行病学调查，该病例在医院候诊区停留约2小时，接触人员包括患者和医务人员。已追踪到密切接触者9人，一般接触者29人，均已落实医学观察和应急接种措施。',
    measures: [
      '追踪密切接触者和暴露人员',
      '开展麻疹疫苗应急接种',
      '医学观察易感接触者',
      '对医疗机构进行消毒',
      '加强预检分诊管理'
    ],
    riskLevel: '中风险',
    createTime: '2025-10-30 15:30',
    updateTime: '2025-10-31 18:00',
    shareCount: 5,
    exportCount: 2
  },
  {
    id: 'INV-2025-1055',
    title: '登革热输入病例调查报告',
    caseInfo: '病例编号: CASE-2025-0075',
    investigator: '流调专员 袁芳',
    investigateTime: '2025-10-28 11:00',
    location: '患者居住地及活动场所',
    status: '已完成',
    priority: '中',
    contactCount: 18,
    closeContactCount: 0,
    summary: '一例东南亚归国人员确诊为登革热。患者回国后3天出现发热、皮疹等症状，实验室检测确诊为登革热病毒感染。调查显示患者在国外疫区有明确蚊虫叮咬史，回国后活动范围有限。已对患者居住地及周边环境开展蚊媒监测和灭蚊工作，未发现本地传播风险。',
    measures: [
      '患者隔离治疗和防蚊隔离',
      '居住地及周边灭蚊处理',
      '开展蚊媒密度监测',
      '清除积水和蚊虫孳生地',
      '向居民宣传登革热防控知识'
    ],
    riskLevel: '低风险',
    createTime: '2025-10-28 11:00',
    updateTime: '2025-10-29 16:45',
    shareCount: 3,
    exportCount: 1
  }
];

// 模拟团队成员数据
const mockTeamMembers = [
  {
    id: 1,
    name: '韩梅',
    role: '流调专员',
    department: '流行病学调查组',
    phone: '139-0000-2001',
    email: 'hanmei@cdc.gov',
    color: '#409EFF'
  },
  {
    id: 2,
    name: '钱峰',
    role: '流调组长',
    department: '流行病学调查组',
    phone: '139-0000-2002',
    email: 'qianfeng@cdc.gov',
    color: '#67C23A'
  },
  {
    id: 3,
    name: '周洁',
    role: '流调专员',
    department: '流行病学调查组',
    phone: '139-0000-2003',
    email: 'zhoujie@cdc.gov',
    color: '#E6A23C'
  },
  {
    id: 4,
    name: '吴雪',
    role: '流调副组长',
    department: '流行病学调查组',
    phone: '139-0000-2004',
    email: 'wuxue@cdc.gov',
    color: '#F56C6C'
  },
  {
    id: 5,
    name: '郑云',
    role: '流调专员',
    department: '流行病学调查组',
    phone: '139-0000-2005',
    email: 'zhengyun@cdc.gov',
    color: '#909399'
  },
  {
    id: 6,
    name: '冯涛',
    role: '流调组长',
    department: '食源性疾病调查组',
    phone: '139-0000-2006',
    email: 'fengtao@cdc.gov',
    color: '#409EFF'
  },
  {
    id: 7,
    name: '叶明',
    role: '流调专员',
    department: '免疫规划调查组',
    phone: '139-0000-2007',
    email: 'yeming@cdc.gov',
    color: '#67C23A'
  },
  {
    id: 8,
    name: '袁芳',
    role: '流调专员',
    department: '虫媒传染病调查组',
    phone: '139-0000-2008',
    email: 'yuanfang@cdc.gov',
    color: '#E6A23C'
  }
];

// 模拟分享历史记录
const mockShareHistory = [
  {
    id: 1,
    reportId: 'INV-2025-1101',
    reportTitle: '新冠肺炎聚集性疫情现场调查报告',
    method: 'team',
    recipients: ['韩梅', '钱峰', '周洁'],
    shareTime: '2025-11-05 16:30',
    status: '已送达'
  },
  {
    id: 2,
    reportId: 'INV-2025-1098',
    reportTitle: '诺如病毒感染聚集性疫情调查',
    method: 'email',
    recipients: ['疾控中心办公室', '应急管理科'],
    shareTime: '2025-11-04 19:00',
    status: '已送达'
  },
  {
    id: 3,
    reportId: 'INV-2025-1095',
    reportTitle: '手足口病疫情现场调查报告',
    method: 'link',
    recipients: ['已生成链接'],
    shareTime: '2025-11-03 15:20',
    status: '已送达'
  },
  {
    id: 4,
    reportId: 'INV-2025-1089',
    reportTitle: '流感样病例聚集性疫情调查',
    method: 'team',
    recipients: ['吴雪', '郑云'],
    shareTime: '2025-11-02 20:30',
    status: '已送达'
  }
];

// 模拟导出历史记录
const mockExportHistory = [
  {
    id: 1,
    reportId: 'INV-2025-1101',
    reportTitle: '新冠肺炎聚集性疫情现场调查报告',
    format: 'PDF',
    exportTime: '2025-11-05 17:00',
    fileSize: '2.3 MB',
    status: '导出成功'
  },
  {
    id: 2,
    reportId: 'INV-2025-1089',
    reportTitle: '流感样病例聚集性疫情调查',
    format: 'Word',
    exportTime: '2025-11-03 10:15',
    fileSize: '1.8 MB',
    status: '导出成功'
  },
  {
    id: 3,
    reportId: 'INV-2025-1089',
    reportTitle: '流感样病例聚集性疫情调查',
    format: 'Excel',
    exportTime: '2025-11-03 10:20',
    fileSize: '0.5 MB',
    status: '导出成功'
  },
  {
    id: 4,
    reportId: 'INV-2025-1075',
    reportTitle: '食源性疾病暴发调查报告',
    format: 'PDF',
    exportTime: '2025-11-01 23:00',
    fileSize: '3.1 MB',
    status: '导出成功'
  }
];

/**
 * 获取调查报告列表
 */
export function getInvestigationReports(params = {}) {
  return new Promise((resolve) => {
    setTimeout(() => {
      let results = [...mockInvestigationReports];
      
      // 按状态筛选
      if (params.status) {
        results = results.filter(r => r.status === params.status);
      }
      
      // 按优先级筛选
      if (params.priority) {
        results = results.filter(r => r.priority === params.priority);
      }
      
      // 按关键词搜索
      if (params.keyword) {
        const keyword = params.keyword.toLowerCase();
        results = results.filter(r => 
          r.title.toLowerCase().includes(keyword) ||
          r.caseInfo.toLowerCase().includes(keyword) ||
          r.location.toLowerCase().includes(keyword) ||
          r.investigator.toLowerCase().includes(keyword)
        );
      }
      
      // 按日期范围筛选
      if (params.startDate && params.endDate) {
        results = results.filter(r => {
          const investigateDate = r.investigateTime.split(' ')[0];
          return investigateDate >= params.startDate && investigateDate <= params.endDate;
        });
      }
      
      resolve(results);
    }, 500);
  });
}

/**
 * 获取单个调查报告详情
 */
export function getReportDetail(reportId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const report = mockInvestigationReports.find(r => r.id === reportId);
      if (report) {
        resolve(report);
      } else {
        reject(new Error('报告不存在'));
      }
    }, 400);
  });
}

/**
 * 保存调查报告
 */
export function saveReport(reportData) {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 模拟保存成功
      resolve({ 
        success: true,
        reportId: reportData.id || `INV-2025-${Math.floor(Math.random() * 10000)}`,
        message: '报告保存成功'
      });
    }, 800);
  });
}

/**
 * 生成分享链接
 */
export function generateShareLink(reportId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const baseUrl = 'https://cdc.gov.cn/investigation/share';
      const token = Math.random().toString(36).substr(2, 16);
      const link = `${baseUrl}/${reportId}?token=${token}&expires=7d`;
      resolve(link);
    }, 800);
  });
}

/**
 * 生成分享文本
 */
export function generateShareText(report) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const text = `【流行病学调查报告】

报告编号：${report.id}
报告标题：${report.title}
病例信息：${report.caseInfo}
调查人员：${report.investigator}
调查时间：${report.investigateTime}
调查地点：${report.location}
风险等级：${report.riskLevel}

调查摘要：
${report.summary}

处置措施：
${report.measures.map((m, i) => `${i + 1}. ${m}`).join('\n')}

接触者统计：
- 接触者总数：${report.contactCount}人
- 密切接触者：${report.closeContactCount}人

---
本报告由疾病预防控制系统生成
生成时间：${new Date().toLocaleString('zh-CN')}`;
      
      resolve(text);
    }, 600);
  });
}

/**
 * 邮件分享报告
 */
export function sendEmailShare(data) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      const emails = data.to.split(',').map(e => e.trim());
      const invalidEmails = emails.filter(e => !emailRegex.test(e));
      
      if (invalidEmails.length > 0) {
        reject(new Error(`无效的邮箱地址: ${invalidEmails.join(', ')}`));
        return;
      }

      const record = {
        id: Date.now(),
        reportId: data.report.id,
        reportTitle: data.report.title,
        method: 'email',
        recipients: emails,
        shareTime: new Date().toLocaleString('zh-CN'),
        status: '已送达'
      };
      
      mockShareHistory.unshift(record);
      resolve({ success: true });
    }, 1000);
  });
}

/**
 * 分享给团队成员
 */
export function shareToTeamMembers(data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const record = {
        id: Date.now(),
        reportId: data.report.id,
        reportTitle: data.report.title,
        method: 'team',
        recipients: data.members.map(m => m.name),
        shareTime: new Date().toLocaleString('zh-CN'),
        status: '已送达'
      };
      
      mockShareHistory.unshift(record);
      resolve({ success: true });
    }, 1000);
  });
}

/**
 * 获取团队成员列表
 */
export function getTeamMembers() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([...mockTeamMembers]);
    }, 500);
  });
}

/**
 * 获取分享历史记录
 */
export function getShareHistory() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([...mockShareHistory]);
    }, 400);
  });
}

/**
 * 导出报告
 */
export function exportReport(reportId, format, options = {}) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const report = mockInvestigationReports.find(r => r.id === reportId);
      
      const record = {
        id: Date.now(),
        reportId: reportId,
        reportTitle: report ? report.title : '未知报告',
        format: format,
        exportTime: new Date().toLocaleString('zh-CN'),
        fileSize: `${(Math.random() * 3 + 0.5).toFixed(1)} MB`,
        status: '导出成功'
      };
      
      mockExportHistory.unshift(record);
      
      resolve({ 
        success: true,
        downloadUrl: `/downloads/${reportId}.${format.toLowerCase()}`,
        fileName: `${report ? report.title : '调查报告'}.${format.toLowerCase()}`,
        fileSize: record.fileSize
      });
    }, 1500);
  });
}

/**
 * 获取导出历史记录
 */
export function getExportHistory() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([...mockExportHistory]);
    }, 400);
  });
}

/**
 * 批量导出报告
 */
export function batchExportReports(reportIds, format) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ 
        success: true,
        downloadUrl: `/downloads/batch_${Date.now()}.zip`,
        fileName: `调查报告批量导出_${new Date().toLocaleDateString()}.zip`,
        count: reportIds.length
      });
    }, 2000);
  });
}

/**
 * 获取报告统计数据
 */
export function getReportStatistics() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        totalReports: mockInvestigationReports.length,
        completedReports: mockInvestigationReports.filter(r => r.status === '已完成').length,
        inProgressReports: mockInvestigationReports.filter(r => r.status === '进行中').length,
        totalContacts: mockInvestigationReports.reduce((sum, r) => sum + r.contactCount, 0),
        totalCloseContacts: mockInvestigationReports.reduce((sum, r) => sum + r.closeContactCount, 0),
        byPriority: {
          high: mockInvestigationReports.filter(r => r.priority === '高').length,
          medium: mockInvestigationReports.filter(r => r.priority === '中').length,
          low: mockInvestigationReports.filter(r => r.priority === '低').length
        },
        byRiskLevel: {
          high: mockInvestigationReports.filter(r => r.riskLevel === '高风险').length,
          medium: mockInvestigationReports.filter(r => r.riskLevel === '中风险').length,
          low: mockInvestigationReports.filter(r => r.riskLevel === '低风险').length
        }
      });
    }, 500);
  });
}

